package com.fmi.timedealer.achievement;

import java.text.DecimalFormat;
import java.util.ArrayList;

import com.fmi.timedealer.R;
import com.fmi.timedealer.datamanager.IDataManager;
import com.fmi.timedealer.datamanager.SQLiteDataManager;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class LevelItemsActivity extends ListActivity {
	
	private ArrayList<AchievementLevelItem> items = null;
	private IDataManager dbManager = null;
	private LevelItemAdapter adapter = null;
	private AchievementLevel currentLevel = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.level_items);
		
		Bundle extras = getIntent().getExtras();
		currentLevel = (AchievementLevel)extras.getSerializable(AchievementsActivity.LEVEL_BUNDLE_KEY);
		
		if (currentLevel != null) {
			this.setTitle(this.getTitle() + " for level " + currentLevel.getLevel() + ": " +
						currentLevel.getName());
		}
		
		dbManager = new SQLiteDataManager("MyDB", this);
		items = dbManager.getLevelItemsForId(currentLevel.getId());
		currentLevel.setItems(items);
	}
	
	private void refreshAdapter() {
		adapter = new LevelItemAdapter(this, R.layout.item_row, items);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		setListAdapter(adapter);
		
		ListView lv = getListView();
		registerForContextMenu(lv);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		refreshAdapter();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.level_item_menu, menu);
	    return true;
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
	        
			case R.id.add_level_item: {
	        	Intent i = new Intent(LevelItemsActivity.this, ManageLevelItemActivity.class);
				i.putExtra(AchievementsActivity.LEVEL_ITEM_BUNDLE_KEY, new AchievementLevelItem());
				i.putExtra(AchievementsActivity.LEVEL_ID_BUNDLE_KEY, currentLevel.getId());
				startActivityForResult(i, AchievementsActivity.ACTION_REQUEST_CODE);
	        	return true;
	        }
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
		menu.setHeaderTitle(items.get(info.position).getActivityItem().getName());
		
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.manage_level_item, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    
		switch (item.getItemId()) {
	        case R.id.edit_level_item: {
	        	Intent i = new Intent(LevelItemsActivity.this, ManageLevelItemActivity.class);
	        	i.putExtra(AchievementsActivity.LEVEL_ID_BUNDLE_KEY, currentLevel.getId());
				i.putExtra(AchievementsActivity.LEVEL_ITEM_BUNDLE_KEY, items.get(info.position));
				startActivityForResult(i, AchievementsActivity.ACTION_REQUEST_CODE);
	        	return true;
	        }
	        case R.id.delete_level_item: {
	            deleteLevelItem(info.position);
	        	return true;
	        }
	        default:
	            return super.onContextItemSelected(item);
	    }
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == AchievementsActivity.ACTION_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				Bundle extras = data.getExtras();
				AchievementLevelItem item = 
						(AchievementLevelItem)extras.getSerializable(AchievementsActivity.LEVEL_ITEM_BUNDLE_KEY);
				
				updateLevelItem(item);
			}
		}
	}
	
	private void updateLevelItem(AchievementLevelItem item) {
		
		int position = -1;
		for (int i = 0; i < items.size(); i++) {
			if (items.get(i).getActivityItem().getId() == item.getActivityItem().getId()) {
				position = i;
				break;
			}
		}
		
		if (position < 0) {
			// Add new object to the collection
			items.add(item);
		}
		else {
			// Update object 
			items.set(position, item);
		}
		currentLevel.setItems(items);
		this.onResume();
		Toast.makeText(this, item.getActivityItem().getName() + " was successfully saved", Toast.LENGTH_SHORT).show();
	}

	private void deleteLevelItem(int position) {
		boolean deleted = dbManager.deleteLevelItem(items.get(position), currentLevel.getId());
		if (deleted) {
			AchievementLevelItem deletedLevelItem = items.get(position);
			items.remove(position);
			refreshAdapter();
			Toast.makeText(this, deletedLevelItem.getActivityItem().getName() + " was successfully deleted", Toast.LENGTH_SHORT).show();
		}
	}
	
	private class LevelItemAdapter extends ArrayAdapter<AchievementLevelItem> {
		
        private ArrayList<AchievementLevelItem> items;

        public LevelItemAdapter(Context context, int textViewResourceId, ArrayList<AchievementLevelItem> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                
        	View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.item_row, null);
                }
                
                AchievementLevelItem item = items.get(position);

                if (item != null) {
                        TextView tvName = (TextView)v.findViewById(R.id.itemName);
                        TextView tvInfo = (TextView)v.findViewById(R.id.itemInfo);
                        TextView tvStatus = (TextView)v.findViewById(R.id.itemStatus);
                        ProgressBar progressBar = (ProgressBar)v.findViewById(R.id.itemProgressBar);
                        int current = item.getGoalTrackTime() - item.getRemainingTime();
                        Double ddd = (double) (((double)current / (double)item.getGoalTrackTime()) * 100);
                        DecimalFormat twoDForm = new DecimalFormat("#.##");
                        ddd = Double.valueOf(twoDForm.format(ddd));
                        double progress = ddd.intValue();

                        progressBar.setProgress((int)progress);
                        if (tvName != null) {
                        	tvName.setText(item.getActivityItem().getName());
                    	}
                        if (tvInfo != null) {
                        	tvInfo.setText(item.getActivityItem().getCategory());
                        }
                        if (tvStatus != null) {
                        	tvStatus.setText("Goal time: " + String.valueOf(item.getGoalTrackTime()) + "h\t " +
                        			("Remaining time: " + String.valueOf(item.getRemainingTime()) + "h"));
                        
                        }
                }
                return v;
        }
	}

}
